<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('课题立项申请')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: select2-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-apply-add">
            <input type="hidden" id="reAmount" name="reAmount">
            <input type="hidden" id="accountData" name="accountData">
            <input type="hidden" id="reamountUrl" name="reamountUrl">
            <input name="amountType" id="amountType" type="hidden" value="1">
            <input type="hidden" id="state" name="state"  value="99">
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">申请人：</label>
                    <div class="col-sm-8">
                        <div th:each="user : ${sysUsers}" th:if="${user.flag}">
                            <input  class="form-control" type="text" th:value="${user.userName}" readonly>
                            <input name="userId" class="form-control" type="hidden" th:value="${user.userId}">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">课题编号：</label>
                    <div class="col-sm-8">
                        <input name="topNumber" class="form-control" type="text"  maxlength="20">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">课题类型：</label>
                    <div class="col-sm-8">
                        <select name="topType" class="form-control" th:with="type=${@dict.getType('sci_top_type')}" required>
                            <option value="" selected>----请选择----</option>
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">课题名称：</label>
                    <div class="col-sm-8">
                        <input name="topName" class="form-control" type="text" required  maxlength="50">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">甲方：</label>
                    <div class="col-sm-8">
                        <input name="partyA" class="form-control" type="text" required  maxlength="20">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">乙方：</label>
                    <div class="col-sm-8">
                        <input name="partyB" class="form-control" type="text" required  maxlength="20">
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">项目金额(万)：</label>
                    <div class="col-sm-8">
                        <div class="input-group ">
                            <input name="amount"  class="form-control" type="number" required step="0.0001" max="999999999">
                            <span class="input-group-addon">
                                <a href="#" title="上传到账金额"  data-toggle="modal" data-target="#myModal"><i class="fa fa-plus-circle" ></i>到账金额</a>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">立项日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input autocomplete="off" name="signingData" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>

<!--            <div class="col-xs-6">-->
<!--                <div class="form-group">-->
<!--                    <label class="col-sm-4 control-label is-required">结项日期：</label>-->
<!--                    <div class="col-sm-8">-->
<!--                        <div class="input-group date">-->
<!--                            <input autocomplete="off" name="validityDate" class="form-control" placeholder="yyyy-MM-dd" type="text" required>-->
<!--                             <span class="input-group-addon"><i class="fa fa-calendar"></i></span>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">主持人：</label>
                    <div class="col-sm-8">
                        <div th:each="user : ${sysUsers}" th:if="${user.flag}">
                            <input  class="form-control" type="text" th:value="${user.userName}" readonly>
                            <input name="firstPersonId" class="form-control" type="hidden" th:value="${user.userId}">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">成员1：</label>
                    <div class="col-sm-8">
                        <select id="member1Select" name="secondPersonId" class="form-control m-b" onchange="updateMemberLists()" required>
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}" th:text="${user.userName}" th:value="${user.userId}"  th:if="${user.userId} != 1 and ${user.flag != true}" ></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">成员2：</label>
                    <div class="col-sm-8">
                        <select id="member2Select" name="thirdPersonId" class="form-control m-b" onchange="updateMemberLists()" required>
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}" th:text="${user.userName}" th:value="${user.userId}" th:if="${user.userId} != 1 and ${user.flag != true}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">成员3：</label>
                    <div class="col-sm-8">
                        <select id="member3Select" name="fourthPersonId" class="form-control m-b" onchange="updateMemberLists()" required>
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}" th:text="${user.userName}" th:value="${user.userId}" th:if="${user.userId} != 1 and ${user.flag != true}"></option>
                        </select>
                    </div>
                </div>

            </div>
            <!-- 第5位及以后：可动态添加 -->
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">更多成员：</label>
                    <div class="col-sm-10">
                        <div id="memberContainer" class="row"></div>
                        <button type="button" id="addMemberBtn" class="btn btn-white btn-sm" title="新增成员">
                            <a href="#"><i class="fa fa-plus-circle" ></i>增加成员</a>
                        </button>
                    </div>
                </div>
            </div>


            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">立项合同：</label>
                    <div class="col-sm-8">
                        <input type="hidden" name="contract">
                        <div class="file-loading">
                            <input class="form-control file-uploada" id="contract" name="file" type="file" >
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">立项备案表：</label>
                    <div class="col-sm-8">
                        <input type="hidden" name="filing">
                        <div class="file-loading">
                            <input class="form-control file-uploadb" id="filing" name="file" type="file" >
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()">    保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"> 关 闭 </button>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: select2-js" />

    <script th:inline="javascript">
        var prefix = ctx + "system/apply"
        $("#form-apply-add").validate({
            focusCleanup: true
        });

        $("input[name='amount']").on('input', function() {
            var value = $(this).val();
            // 限制整数部分不超过9位
            if (value) {
                var numericValue = parseFloat(value);
                // 限制整数部分长度
                if (value.indexOf('.') !== -1) {
                    var parts = value.split('.');
                    if (parts[0].length > 9) {
                        $(this).val(parts[0].substring(0, 9) + (parts[1] ? '.' + parts[1] : ''));
                    }
                } else {
                    if (value.length > 9) {
                        $(this).val(value.substring(0, 9));
                    }
                }
                // 限制小数点后只能输入四位
                if (value.indexOf('.') !== -1) {
                    var parts = value.split('.');
                    if (parts[1] && parts[1].length > 4) {
                        $(this).val(parts[0] + '.' + parts[1].substring(0, 4));
                    }
                }
                // 限制最大值
                var valueStr = numericValue.toString();
                if (valueStr.length > 9){
                    this.value = "";
                    $.modal.alertError("输入金额有误差：总长度最大9位数，小数点后最大四位；例：9999.9999")
                }
            }
        });

        function submitHandler() {
            if ($.validate.form()){
                var firstPersonId = document.querySelector('input[name="firstPersonId"]').value;
                var secondPersonId = document.querySelector('select[name="secondPersonId"]').value;
                var thirdPersonId = document.querySelector('select[name="thirdPersonId"]').value;
                var fourthPersonId = document.querySelector('select[name="fourthPersonId"]').value;

                // 先收集前四位（主持人 + 成员1/2/3）
                var personIds = [firstPersonId, secondPersonId, thirdPersonId, fourthPersonId];

                // 再收集第5位及以后的动态成员（过滤空）
                $('.member-select').each(function(){
                    var val = $(this).val();
                    if (val) personIds.push(val);
                });

                // 校验项目金额不能为负数
                var projectAmount = $("input[name='amount']").val();
                if (parseFloat(projectAmount) <= 0) {
                    return $.modal.alertError("请输入有效的项目金额");
                }

                // 校验项目金额小数点后最多4位
                if (!/^\d+(\.\d{1,4})?$/.test(projectAmount)) {
                    return $.modal.alertError("项目金额小数点后最多4位");
                }


                // 将成员数组写入隐藏域，便于后端接收
                // 若后端用 RequestParam 接收，可使用逗号拼接；若用数组接收，也可直接 form 序列化多个 name=members
                // 这里采用 name="members" 多值方式，无需额外隐藏域

                if($("input[name='contract']").val()==="")
                    return $.modal.alertError("请上传合同");
                if($("input[name='filing']").val()==="")
                    return $.modal.alertError("请上传备案表");

                // 校验课题名称、甲方、乙方不能包含特殊字符
                var topName = $("input[name='topName']").val();
                var partyA = $("input[name='partyA']").val();
                var partyB = $("input[name='partyB']").val();
                var specialCharPattern = /[@#￥%&*$!]/;

                if (specialCharPattern.test(topName)) {
                    return $.modal.alertError("课题名称不能包含特殊字符");
                }
                if (topName === "") {
                    return $.modal.alertError("课题名称不能为空或纯空格");
                }
                if (specialCharPattern.test(partyA)) {
                    return $.modal.alertError("甲方不能包含特殊字符");
                }
                if (specialCharPattern.test(partyB)) {
                    return $.modal.alertError("乙方不能包含特殊字符");
                }
                if (topName.length > 50) {
                    return $.modal.alertError("课题名称不能超过50个字符");
                }
                if (partyA && partyA.length > 20) {
                    return $.modal.alertError("甲方不能超过20个字符");
                }
                if (partyB && partyB.length > 20) {
                    return $.modal.alertError("乙方不能超过20个字符");
                }
                $.operate.saveTab(prefix + "/add", $('#form-apply-add').serialize());
            }
        }


        $("input[name='signingData']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='validityDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(".file-uploada").fileinput({
            uploadUrl: ctx + 'common/upload/hxkt',
            initialPreviewAsData: true,
            maxFileCount: 1,
        maxFileSize: 51200,
            autoReplace: true,
            allowedFileExtensions: ["pdf"],
            slugCallback: function(filename) {
                if ($("input[name='topName']").val()===""){
                    $(".file-uploada").fileinput('clear');
                    $.modal.alertError("请先输入课题名称");
                    return false;
                }
                // 自定义文件名生成规则
                fileExtension = filename.split('.').pop();
                const year = new Date().getFullYear();
                const newName = year +"-"+ $("input[name='topName']").val() +"-"+ "立项合同"+ "." + fileExtension;
                return newName;
            },
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })
        $(".file-uploadb").fileinput({
            uploadUrl: ctx + 'common/upload/hxkt',
            initialPreviewAsData: true,
            maxFileCount: 1,
        maxFileSize: 51200,
            autoReplace: true,
            allowedFileExtensions: ["pdf"],
            slugCallback: function(filename) {
                if ($("input[name='topName']").val()===""){
                    $(".file-uploadb").fileinput('clear');
                    $.modal.alertError("请先输入课题名称");
                    return false;
                }
                // 自定义文件名生成规则
                fileExtension = filename.split('.').pop();
                const year = new Date().getFullYear();
                const newName = year +"-"+ $("input[name='topName']").val() +"-"+ "立项备案表"+ "." + fileExtension;
                return newName;
            },
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })
                // 动态新增成员下拉（第5位起）

        $('#addMemberBtn').on('click', function(){

            // 获取原始选项数据

            var originalOptions = $('#member1Select').data('original-options');

            var memberCount = $('.member-item').length + 1; // 计算当前成员数量

            var memberId = 'dynamicMember' + memberCount; // 为每个动态成员生成唯一ID

            

            var tpl = '\
            <div class="col-xs-3 m-b-xs member-item">\
                <div class="input-group">\
                    <select id="' + memberId + '" name="members" class="form-control m-b member-select select2-select" onchange="updateMemberLists()">\
                        <option value="">---请选择--</option>\
                    </select>\
                    <span class="input-group-btn">\
                        <button class="btn btn-danger btn-sm remove-member" type="button" title="移除"><i class="fa fa-minus"></i></button>\
                    </span>\
                </div>\
            </div>';

            $('#memberContainer').append(tpl);

            // 初始化新添加的下拉框选项
            updateDynamicMemberList($('#' + memberId)[0]);

            // 初始化Select2
            $('#' + memberId).select2({
                placeholder: "---请选择--",
                allowClear: true,
                width: "100%"
            });
        });

        // 移除成员项
        $(document).on('click', '.remove-member', function(){
            $(this).closest('.member-item').remove();
        });

        

        // 成员下拉框联动功能
        // 页面加载完成后保存原始选项并初始化联动
        $(document).ready(function() {
            // 保存原始选项数据
            $('#member1Select, #member2Select, #member3Select').each(function() {
                var originalOptions = $(this).html();
                $(this).data('original-options', originalOptions);
            });

            

            // 初始化联动效果
            updateMemberLists();


            // 初始化Select2组件以支持搜索功能
            $('#member1Select, #member2Select, #member3Select').select2({
                placeholder: "---请选择--",
                allowClear: true,
                width: "100%"
            });
        });

        

        // 更新成员下拉框列表
        function updateMemberLists() {
            // 获取所有已选中的成员ID（使用Set自动去重）
            var selectedIds = new Set();


            // 获取三个固定成员下拉框的值
            var member1Value = $('#member1Select').val();
            var member2Value = $('#member2Select').val();
            var member3Value = $('#member3Select').val();


            // 将非空值添加到Set中
            if (member1Value) selectedIds.add(member1Value);
            if (member2Value) selectedIds.add(member2Value);
            if (member3Value) selectedIds.add(member3Value);


            // 添加动态成员的选中值
            $('.member-select').each(function() {
                var value = $(this).val();
                if (value) {
                    selectedIds.add(value);
                }
            });


            // 为每个固定下拉框更新选项
            updateSelectOptions('#member1Select', member1Value, selectedIds);
            updateSelectOptions('#member2Select', member2Value, selectedIds);
            updateSelectOptions('#member3Select', member3Value, selectedIds);


            // 为每个动态下拉框更新选项
            $('.member-select').each(function() {
                updateDynamicSelectOptions($(this), $(this).val(), selectedIds);
            });
        }

        

        // 更新单个下拉框的选项
        function updateSelectOptions(selectId, currentValue, selectedIds) {

            var selectElement = $(selectId);
            var originalOptions = selectElement.data('original-options');
            var isCurrentlySelected = selectElement.val(); // 保存当前选中的值

            // 清空当前选项（保留第一个提示选项）
            selectElement.find('option:not(:first)').remove();


            // 解析原始选项
            var tempDiv = $('<div>' + originalOptions + '</div>');
            var hasBlankOption = false; // 标记是否已添加空选项
            tempDiv.find('option').each(function() {
                var option = $(this);
                var value = option.val();
                // 只有当选项值为空（请选择）或未被其他下拉框选中时才添加
                // currentValue（当前下拉框已选中的值）总是会被保留，如果它不在其他下拉框中
                if (value === "" && !hasBlankOption) {
                    // 只添加一次空选项
                    selectElement.append(option.clone());
                    hasBlankOption = true;
                } else if (value !== "" && (!selectedIds.has(value) || value === currentValue || value === "-1")) {
                    // 添加非空选项，如果它未被其他下拉框选中，或者是当前下拉框已选中的值，或者userId为-1（其他）
                    selectElement.append(option.clone());
                }
            });

            // 重新设置选中状态，确保选中的值仍然被选中
            if (isCurrentlySelected) {
                selectElement.val(isCurrentlySelected);
            }
        }


        // 更新动态添加的成员下拉框
        function updateDynamicMemberList(element) {
            var selectElement = $(element);
            var currentValue = selectElement.val();
            var allSelectedIds = getSelectedIds();

            // 为动态成员下拉框更新选项
            updateDynamicSelectOptions(selectElement, currentValue, allSelectedIds);
        }

        

        // 获取所有已选中的ID（包括固定成员和动态成员）
        function getSelectedIds() {
            var selectedIds = new Set();

            // 添加固定成员的选中值
            var member1Value = $('#member1Select').val();
            var member2Value = $('#member2Select').val();
            var member3Value = $('#member3Select').val();

            if (member1Value) selectedIds.add(member1Value);
            if (member2Value) selectedIds.add(member2Value);
            if (member3Value) selectedIds.add(member3Value);


            // 添加动态成员的选中值
            $('.member-select').each(function() {
                var value = $(this).val();
                if (value) {
                    selectedIds.add(value);
                }
            });
            return selectedIds;
        }

        

        // 更新动态下拉框的选项
        function updateDynamicSelectOptions(selectElement, currentValue, selectedIds) {
            var originalOptions = $('#member1Select').data('original-options');
            var isCurrentlySelected = selectElement.val(); // 保存当前选中的值


            // 清空当前选项（保留第一个提示选项）
            selectElement.find('option:not(:first)').remove();
            // 解析原始选项
            var tempDiv = $('<div>' + originalOptions + '</div>');
            var hasBlankOption = false; // 标记是否已添加空选项
            tempDiv.find('option').each(function() {
                var option = $(this);
                var value = option.val();
                // 只有当选项值为空（请选择）或未被其他下拉框选中时才添加
                // currentValue（当前下拉框已选中的值）总是会被保留，如果它不在其他下拉框中
                if (value === "" && !hasBlankOption) {
                    // 只添加一次空选项
                    selectElement.append(option.clone());
                    hasBlankOption = true;
                } else if (value !== "" && (!selectedIds.has(value) || value === currentValue || value === "-1")) {
                    // 添加非空选项，如果它未被其他下拉框选中，或者是当前下拉框已选中的值，或者userId为-1（其他）
                    selectElement.append(option.clone());
                }
            });

            // 重新设置选中状态，确保选中的值仍然被选中
            if (isCurrentlySelected) {
                selectElement.val(isCurrentlySelected);
            }
        }
    </script>
</body>
<body>
<style>
    .modal.inmodal .modal-dialog {
        width: auto;  /* 宽度自适应 */
        max-width: 50%;  /* 最大宽度限制，避免过宽 */
    }
    .modal.inmodal .modal-content {
        height: 800px;
    }
    /* 使模态框的内容区域自适应高度 */
    .modal-body {
        height: 500px;  /* 最大高度，避免溢出屏幕 */
        overflow-y: auto;  /* 如果内容超出高度，显示滚动条 */
    }
    .form-group-spacing {
        margin-bottom: 10px; /* 你可以根据需要调整这个值 */
    }
</style>
<div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated bounceInRight">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">关闭</span>
                </button>
                <i class="fa fa-laptop modal-icon"></i>
                <h4 class="modal-title">提交到账金额</h4>
                <!--                <small class="font-bold">需要到账金额文件为佐证材料！</small>-->
            </div>
            <form class="form-horizontal m" id="form-apply-add1">
                <div class="modal-body">
                    <div class="col-xs-10">
                        <div class="form-group">
                            <label class="col-sm-4 control-label is-required">项目金额(万)：</label>
                            <div class="col-sm-8">
                                <input name="reAmount1" class="form-control" type="number" required step="0.0001" maxlength="9">
                            </div>
                        </div>
                    </div>

                    <div class="col-xs-10">
                        <div class="form-group">
                            <label class="col-sm-4 control-label is-required">到账日期：</label>
                            <div class="col-sm-8">
                                <div class="input-group date">
                                    <input name="accountData1" autocomplete="off"  class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group-spacing" ></div>

                    <div class="col-xs-10">
                        <div class="form-group">
                            <label class="col-sm-4 control-label is-required">到账文件：</label>
                            <div class="col-sm-8">
                                <input type="hidden" name="reamountUrl1">
                                <div class="file-loading">
                                    <input class="form-control amountfile-upload" id="reamountUrl1" name="file" type="file" >
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" id="close" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitAmount()">保存</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("input[name='reAmount1']").on('input', function() {
        var value = $(this).val();
        // 限制整数部分不超过9位
        if (value) {
            var numericValue = parseFloat(value);
            // 限制整数部分长度
            if (value.indexOf('.') !== -1) {
                var parts = value.split('.');
                if (parts[0].length > 9) {
                    $(this).val(parts[0].substring(0, 9) + (parts[1] ? '.' + parts[1] : ''));
                }
            } else {
                if (value.length > 9) {
                    $(this).val(value.substring(0, 9));
                }
            }
            // 限制小数点后只能输入四位
            if (value.indexOf('.') !== -1) {
                var parts = value.split('.');
                if (parts[1] && parts[1].length > 4) {
                    $(this).val(parts[0] + '.' + parts[1].substring(0, 4));
                }
            }
            // 限制最大值
            var valueStr = numericValue.toString();
            if (valueStr.length > 9){
                this.value = "";
                $.modal.alertError("输入金额有误差：总长度最大9位数，小数点后最大四位；例：9999.9999")
            }
        }
    });

    function submitAmount() {
        var reAmount1 = $("input[name='reAmount1']").val();
        var accountData1 = $("input[name='accountData1']").val();
        var reamountUrl1 = $("input[name='reamountUrl1']").val();
        var projectAmount = $("input[name='amount']").val(); // 获取项目金额

        if (reAmount1 === "") {
            return $.modal.alertError("请添加到账金额");
        }

        // 校验到账金额不能为负数
        if (parseFloat(reAmount1) < 0 || parseFloat(reAmount1) == 0) {
            return $.modal.alertError("请输入正确的金额");
        }

        // 校验到账金额不能大于项目金额的
        if (projectAmount !== undefined && projectAmount !== "") {
            var maxAmount = parseFloat(projectAmount);
            if (parseFloat(reAmount1) > maxAmount) {
                return $.modal.alertError("到账金额不能大于项目金额");
            }
        }

        // 去除前后空格并转换为字符串
        var value = reAmount1.trim();

        // 判断是否是有效数字
        if (isNaN(value)) {
            return $.modal.alertError("请输入有效的数字");
        }

        // 全由0组成（包括整数和小数形式）
        if (/^0+(\.0+)?$/.test(value)) {
            return $.modal.alertError("到账金额不能为零");
        }

        if (accountData1 === "") {
            return $.modal.alertError("请添加到账时间");
        }

        if (reamountUrl1 === "") {
            return $.modal.alertError("请上传到账金额文件");
        }

        if (reAmount1 && accountData1 && reamountUrl1) {
            $("#reAmount").val(reAmount1);
            $("#accountData").val(accountData1);
            $("#reamountUrl").val(reamountUrl1);
            $("#close").click();
        } else {
            return $.modal.alertError("上传信息有误");
        }
    }


    $("input[name='accountData1']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });


    $(".amountfile-upload").fileinput({
        uploadUrl: ctx + 'common/upload/hxkt',
        initialPreviewAsData: true,
        maxFileCount: 1,
        maxFileSize: 51200,
        autoReplace: true,
        allowedFileExtensions: ["pdf"],
        slugCallback: function(filename) {
            if ($("input[name='reAmount1']").val()===""){
                $(".amountfile-upload").fileinput('clear');
                $.modal.alertError("请先输入到账金额");
                return false;
            }
            // 自定义文件名生成规则
            fileExtension = filename.split('.').pop();
            const year = new Date().getFullYear();
            const newName = year +"-"+ $("input[name='topName']").val() +"-"+ "金额佐证材料"+ "." + fileExtension;
            return newName;
        },
    }).on('fileuploaded', function (event, data, previewId, index) {
        $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
    })

</script>
</body>
</html>